const Request = require('../request')
const CONSTNAT = require('./constant')

/**
 * 构造查询Url
 * @param type search type. eg. project; merge_request
 * @param scope search scope. eg. issue; note
 * @param search string
 * @returns {string} url
 */
function buildSearchUrl(type, scope, search, page = 1, perpage = 20) {
  // type => url types
  const Types = {
    'project': 'projects'
  }

  if (!type || !scope) {
    // eslint-disable-next-line no-throw-literal
    throw `Invalid type: ${type} or scope: ${scope}`
  }

  if (!Types[type] || !CONSTNAT.SEARCH_URL[scope.toUpperCase()]) {
    // eslint-disable-next-line no-throw-literal
    throw `Invalid type: ${type} or scope: ${scope}`
  }

  if (CONSTNAT.PROJECT_NAMES[0].indexOf('/') > 0) {
    CONSTNAT.PROJECT_NAMES[0] = encodeURIComponent(CONSTNAT.PROJECT_NAMES[0])
  }

  function replace() {
    return CONSTNAT.SEARCH_URL[scope.toUpperCase()].replace('{{SEARCH}}', encodeURIComponent(search)).replace('{{PAGE}}', page).replace('{{PER_PAGE}}', perpage)
  }

  return `${CONSTNAT.HOST}/api/${CONSTNAT.VERSION}/${Types[type]}/${CONSTNAT.PROJECT_NAMES[0]}/${replace()}`
}

/**
 * 构造issues相关的Url: https://git.huawei.com/help/api/issues.md
 * @param type issues type. eg. single
 * @param iid issues id
 * @returns {string} url
 */
function buildIssuesUrl(type, iid) {
  const validTypes = ['single']
  if (type && validTypes.includes(type)) {
    return `${CONSTNAT.HOST}/api/${CONSTNAT.VERSION}/projects/${CONSTNAT.PROJECT_NAMES[0]}/${CONSTNAT.ISSUES_URL[type.toUpperCase()].replace('{{IID}}', iid)}`
  }
  throw new Error(`Invalid type: ${type}. And valid types: ${validTypes.toString()}`)
}

function request(url) {
  return Request.get(url, { 'PRIVATE-TOKEN': 'emzUMN1qQyZoayEY258n' })
}

module.exports = {
  buildSearchUrl,
  buildIssuesUrl,
  request
}
